<template>
  <div class="drones-container">
    <div class="page-header">
      <h2>无人机管理</h2>
      <el-button type="primary" @click="handleAddDrone" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加无人机
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="无人机编号">
          <el-input
            v-model="searchForm.drone_code"
            placeholder="请输入无人机编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="型号">
          <el-select
            v-model="searchForm.drone_type_id"
            placeholder="请选择型号"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="type in droneTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="status in statusDict"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select
            v-model="searchForm.department_id"
            placeholder="请选择部门"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
          <el-button @click="resetSearch"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 无人机表格 -->
    <el-card class="drones-table-card" shadow="hover">
      <el-table
        :data="dronesData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="drone_code" label="无人机编号" width="150" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="drone_type_name" label="型号" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.drone_type_name || "-" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              :effect="getStatusTagEffect(row.status)"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="battery_level" label="电池电量" width="100">
          <template #default="{ row }">
            <div class="battery-level">
              <el-progress
                :percentage="row.battery_level"
                :color="getBatteryColor(row.battery_level)"
                :format="() => `${row.battery_level}%`"
                size="small"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="department_name" label="所属部门" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
              :disabled="viewingId === row.id"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleEditDrone(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteDrone(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑无人机对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加无人机' : '编辑无人机'"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="droneForm"
        :rules="droneRules"
        ref="droneFormRef"
        label-width="120px"
        class="drone-form"
      >
        <el-form-item label="无人机编号" prop="drone_code">
          <el-input
            v-model="droneForm.drone_code"
            placeholder="请输入无人机编号"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="droneForm.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="型号" prop="drone_type_id">
          <el-select
            v-model="droneForm.drone_type_id"
            placeholder="请选择型号"
            clearable
          >
            <el-option
              v-for="type in droneTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属部门" prop="department_id">
          <el-select
            v-model="droneForm.department_id"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="操作员" prop="operator_id">
          <el-select
            v-model="droneForm.operator_id"
            placeholder="请选择操作员"
            clearable
          >
            <el-option
              v-for="operator in operators"
              :key="operator.id"
              :label="operator.name"
              :value="operator.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="droneForm.status" placeholder="请选择状态">
            <el-option
              v-for="status in statusDict"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="电池电量" prop="battery_level">
          <el-slider
            v-model="droneForm.battery_level"
            :min="0"
            :max="100"
            show-input
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="droneForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 无人机详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="无人机详情"
      width="700px"
      destroy-on-close
    >
      <el-descriptions border :column="2" class="drone-detail">
        <el-descriptions-item label="无人机编号">{{
          currentDrone.drone_code
        }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{
          currentDrone.name
        }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{
          currentDrone.drone_type_name
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
            :type="getStatusTagType(currentDrone.status)"
            :effect="getStatusTagEffect(currentDrone.status)"
          >
            {{ getStatusText(currentDrone.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="电池电量"
          >{{ currentDrone.battery_level }}%</el-descriptions-item
        >
        <el-descriptions-item label="所属部门">{{
          currentDrone.department_name
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          currentDrone.created_at
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          currentDrone.updated_at || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{
          currentDrone.description || "-"
        }}</el-descriptions-item>
      </el-descriptions>

      <div class="recent-records">
        <h4>最近飞行记录</h4>
        <el-table
          :data="currentDrone.recent_records || []"
          style="width: 100%"
          size="small"
        >
          <el-table-column prop="record_time" label="时间" width="150" />
          <el-table-column prop="flight_time" label="飞行时长" width="100" />
          <el-table-column
            prop="flight_distance"
            label="飞行距离"
            width="100"
          />
          <el-table-column prop="operator" label="操作人" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from '@/utils/request';

export default {
  name: "Drones",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const detailVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const droneFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);
    const viewingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      drone_code: "",
      drone_type_id: "",
      status: "",
      department_id: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 无人机表单
    const droneForm = reactive({
      id: "",
      drone_code: "",
      name: "",
      drone_type_id: "",
      department_id: "",
      operator_id: "",
      status: "idle",
      battery_level: 100,
      description: "",
    });

    // 当前查看的无人机详情
    const currentDrone = reactive({});

    // 表单验证规则
    const droneRules = {
      drone_code: [
        { required: true, message: "请输入无人机编号", trigger: "blur" },
      ],
      name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      drone_type_id: [
        { required: true, message: "请选择型号", trigger: "change" },
      ],
    };

    // 从API获取的数据
    const droneTypes = ref([]);
    const departments = ref([]);
    const statusDict = ref([]);
    const dronesData = ref([]);
    const operators = ref([]);

    // 获取无人机类型列表
    const fetchDroneTypes = async () => {
      try {
        const response = await service.get("/drone-types", {
          params: {
            page_size: 100,
          }
        });

        // 正确处理响应格式并确保数据安全
        let items = [];
        if (response.code == "200") {
          items = response.data.items;
        }
        
        // 确保数据安全，只使用必要的属性
        droneTypes.value = items.map(type => ({
          id: type.id,
          name: type.name
        }));
      } catch (error) {
        console.error("获取无人机类型数据失败:", error);
      }
    };

    // 获取部门列表
    const fetchDepartments = async () => {
      try {
        const response = await service.get("/departments", {
          params: {
            page_size: 100,
          }
        });

        // 正确处理响应格式并确保数据安全
        let items = [];
        if (response.code == "200") {
          items = response.data;
        }
        
        // 确保数据安全，只使用必要的属性
        departments.value = items.map(dept => ({
          id: dept.id,
          name: dept.name
        }));
      } catch (error) {
        console.error("获取部门数据失败:", error);
      }
    };

    // 获取状态字典
    const fetchStatusDict = async () => {
      try {
        // 状态字典数据，这里使用硬编码的方式，实际应该从API获取
        statusDict.value = [
          { label: '空闲', value: 'idle' },
          { label: '飞行中', value: 'flying' },
          { label: '维修中', value: 'maintenance' },
          { label: '停用', value: 'deactivated' },
          { label: '忙碌', value: 'busy' }
        ];
      } catch (error) {
        console.error("获取状态字典失败:", error);
        statusDict.value = [];
      }
    };

    // 获取操作员列表
    const fetchOperators = async () => {
      try {
        const response = await service.get("/users", {
          params: {
            page_size: 100, // 后端限制最大为100
          }
        });

        // 正确处理响应格式并确保数据安全
        let items = [];
        if (response.code == "200") {
          items = response.data.items;
        }
        
        // 确保数据安全，只使用必要的属性
        operators.value = items.map(operator => ({
          id: operator.id,
          name: operator.username
        }));
      } catch (error) {
        console.error("获取操作员数据失败:", error);
      }
    };

    // 初始化
    onMounted(async () => {
      // 并行获取所有基础数据
      await Promise.all([
        fetchDroneTypes(),
        fetchDepartments(),
        fetchStatusDict(),
        fetchOperators(),
      ]);
      // 基础数据加载完成后获取无人机列表
      fetchDrones();
    });

    // 获取无人机列表
    const fetchDrones = async () => {
      loading.value = true;
      try {
        // 准备查询参数
        const params = {
          page: pagination.currentPage,
          page_size: pagination.pageSize,
          serial_number: searchForm.drone_code || undefined,
          status: searchForm.status || undefined,
        };

        // 发送API请求
        const response = await service.get("/drones", {
          params
        });

        // 正确处理响应格式
        let items = [];
        let total = 0;
        
        // 适配多种响应格式
        if (response && response.data && response.data.items) {
          items = response.data.items;
          total = response.data.total || 0;
        } else if (response && response.items) {
          items = response.items;
          total = response.total || 0;
        }

        // 转换后端数据格式为前端需要的格式
        dronesData.value = items.map((drone) => ({
          id: drone.id,
          name: drone.name || '未命名',
          drone_code: drone.serial_number || drone.drone_code || '',
          drone_type_id: drone.drone_type_id,
          drone_type_name: drone.drone_type?.name || drone.drone_type_name || "未知型号",
          department_id: drone.operator?.department_id || drone.department_id || null,
          department_name: drone.operator?.department?.name || drone.department_name || "无部门",
          operator_id: drone.operator_id,
          operator_name: drone.operator?.name || drone.operator_name || "无操作员",
          status: drone.status || "idle", // 使用与statusDict匹配的默认值
          battery_level: drone.battery_level || 0,
          created_at: drone.created_at ? new Date(drone.created_at).toLocaleString("zh-CN") : '',
          description: drone.description || "",
        }));

        // 更新分页信息
        pagination.total = total;
      } catch (error) {
        console.error("获取无人机列表失败:", error);
        ElMessage.error("获取无人机列表失败");
        // 提供空数组确保表格不会因数据问题崩溃
        dronesData.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      // 确保status参数有效
      if (!status || typeof status !== 'string') {
        return '未知状态';
      }
      
      try {
        // 先检查statusDict是否有效且为数组
        if (Array.isArray(statusDict.value) && statusDict.value.length > 0) {
          const statusItem = statusDict.value.find((item) => item?.value === status);
          if (statusItem && statusItem.label) {
            return statusItem.label;
          }
        }
        // 使用更全面的默认映射，包含可能的后端状态值
        const statusMap = {
          normal: "正常",
          maintenance: "维护中",
          fault: "故障",
          broken: "故障",
          disabled: "停用",
          deactivated: "停用",
          idle: "空闲",
          flying: "飞行中",
          available: "可用",
        };
        return statusMap[status] || '未知状态';
      } catch (error) {
        console.error('获取状态文本时出错:', error);
        return '未知状态';
      }
    };

    // 获取状态标签类型
    const getStatusTagType = (status) => {
      // 确保status参数有效
      if (!status || typeof status !== 'string') {
        return "info";
      }
      
      try {
        // 检查statusDict是否有效且为数组
        if (Array.isArray(statusDict.value) && statusDict.value.length > 0) {
          const statusItem = statusDict.value.find((item) => item?.value === status);
          if (statusItem && statusItem.type) {
            return statusItem.type;
          }
        }
        // 使用更全面的默认映射
        const typeMap = {
          normal: "success",
          maintenance: "warning",
          fault: "danger",
          broken: "danger",
          disabled: "info",
          deactivated: "info",
          idle: "success",
          flying: "primary",
          available: "success",
        };
        return typeMap[status] || "info";
      } catch (error) {
        console.error('获取状态标签类型时出错:', error);
        return "info";
      }
    };

    // 获取状态标签效果
    const getStatusTagEffect = (status) => {
      try {
        return status === "flying" ? "dark" : "light";
      } catch (error) {
        console.error('获取状态标签效果时出错:', error);
        return "light";
      }
    };

    // 获取电池颜色
    const getBatteryColor = (level) => {
      if (level > 70) return "#67c23a";
      if (level > 30) return "#e6a23c";
      return "#f56c6c";
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchDrones();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = "";
      });
      pagination.currentPage = 1;
      fetchDrones();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchDrones();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchDrones();
    };

    // 打开添加无人机对话框
    const handleAddDrone = () => {
      dialogType.value = "add";
      resetDroneForm();
      dialogVisible.value = true;
    };

    // 打开编辑无人机对话框
    const handleEditDrone = (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;
      // 复制数据
      Object.assign(droneForm, row);
      dialogVisible.value = true;
    };

    // 查看无人机详情
    const handleViewDetail = (row) => {
      viewingId.value = row.id;
      // 复制数据并添加最近记录
      Object.assign(currentDrone, row, {
        recent_records: [
          {
            record_time: "2024-01-19 10:00",
            flight_time: "45分钟",
            flight_distance: "15km",
            operator: "pilot01",
          },
          {
            record_time: "2024-01-18 14:30",
            flight_time: "30分钟",
            flight_distance: "10km",
            operator: "pilot02",
          },
          {
            record_time: "2024-01-17 09:15",
            flight_time: "60分钟",
            flight_distance: "20km",
            operator: "pilot01",
          },
        ],
      });
      detailVisible.value = true;
    };

    // 删除无人机
    const handleDeleteDrone = (row) => {
      ElMessageBox.confirm(`确定要删除无人机「${row.name}」吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            // 调用删除API
            const response = await service.delete(`/drones/${row.id}`);

            if (response.data.code === 200) {
              ElMessage.success("删除成功");
              fetchDrones();
            } else {
              throw new Error(response.data.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            ElMessage.error(error.message || "删除失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
        });
    };

    // 重置无人机表单
    const resetDroneForm = () => {
      if (droneFormRef.value) {
        droneFormRef.value.resetFields();
      }
      Object.assign(droneForm, {
        id: "",
        drone_code: "",
        name: "",
        drone_type_id: "",
        department_id: "",
        operator_id: "",
        status: "idle",
        battery_level: 100,
        description: "",
      });
    };

    // 提交表单
    const handleSubmit = () => {
      droneFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            // 准备请求数据
            const formData = {
              name: droneForm.name,
              serial_number: droneForm.drone_code,
              drone_type_id: droneForm.drone_type_id,
              department_id: droneForm.department_id || null,
              operator_id: droneForm.operator_id || null,
              status:
                {
                  idle: "available",
                  flying: "busy",
                  maintenance: "maintenance",
                  fault: "broken",
                  normal: "available",
                  disabled: "disabled",
                }[droneForm.status] || "available",
              battery_level: droneForm.battery_level,
            };

            if (dialogType.value === "add") {
              // 调用添加API
              const response = await service.post("/drones", formData);

              if (response.data.code === 200) {
                ElMessage.success("添加成功");
              } else {
                throw new Error(response.data.message || "添加失败");
              }
            } else {
              // 调用编辑API
              const response = await service.put(
                `/drones/${droneForm.id}`,
                formData
              );

              if (response.code === 200) {
                ElMessage.success("更新成功");
              } else {
                throw new Error(response.message || "更新失败");
              }
            }

            dialogVisible.value = false;
            fetchDrones();
          } catch (error) {
            console.error("操作失败:", error);
            ElMessage.error(error.message || "操作失败");
          } finally {
            dialogLoading.value = false;
            editingId.value = null;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      detailVisible,
      dialogType,
      dialogLoading,
      droneFormRef,
      searchForm,
      pagination,
      droneForm,
      droneRules,
      droneTypes,
      departments,
      statusDict,
      dronesData,
      operators,
      currentDrone,
      editingId,
      deletingId,
      viewingId,
      getStatusText,
      getStatusTagType,
      getStatusTagEffect,
      getBatteryColor,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddDrone,
      handleEditDrone,
      handleViewDetail,
      handleDeleteDrone,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.drones-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.drones-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drone-form .el-form-item {
  margin-bottom: 20px;
}

.battery-level {
  width: 100%;
  padding: 0 10px;
}

.drone-detail {
  margin-bottom: 20px;
}

.recent-records {
  margin-top: 30px;
}

.recent-records h4 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}
</style>
